<template>
  <view class="post-detail">
    <!-- 顶部导航栏 -->
    <view class="navbar">
      <view class="back-btn" @click="goBack">
        <wd-icon name="arrow-left" size="20" color="#333" />
      </view>
      <view class="navbar-title">帖子详情</view>
      <view class="more-btn" @click="showMoreActions">
        <wd-icon name="more" size="20" color="#333" />
      </view>
    </view>

    <!-- 帖子内容 -->
    <view v-if="postDetail" class="post-content">
      <view class="post-header">
        <view class="user-info">
          <image
            class="avatar"
            :src="postDetail.avatar || 'https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/3837e31b236d46578dcc41d49904568e.png'"
            mode="aspectFill"
            @tap="viewUserProfile(postDetail.userId)"
          />
          <view class="user-name-time">
            <view class="user-name" @tap="viewUserProfile(postDetail.userId)">
              {{ postDetail.userName }}
            </view>
            <view class="post-time">{{ postDetail.publishTime }}</view>
          </view>
        </view>
        <view v-if="postDetail.tag" class="post-tag">{{ postDetail.tag }}</view>
      </view>

      <view class="post-body">
        <view class="post-title">{{ postDetail.title }}</view>
        <view class="post-text">{{ postDetail.content }}</view>

        <!-- 帖子图片 -->
        <view v-if="postDetail.images && postDetail.images.length > 0" class="post-images">
          <image
            v-for="(img, index) in postDetail.images"
            :key="index"
            :src="img"
            mode="widthFix"
            class="post-image"
            @tap="previewImage(postDetail.images, index)"
          />
        </view>

        <!-- 帖子位置信息 -->
        <view v-if="postDetail.location" class="post-location">
          <wd-icon name="location" size="14" color="#999" />
          <text>{{ postDetail.location }}</text>
        </view>
      </view>

      <!-- 交互按钮 -->
      <view class="post-actions">
        <view class="action-item" @click="handleLike">
          <wd-icon
            :name="postDetail.isLiked ? 'heart-filled' : 'heart'"
            :color="postDetail.isLiked ? '#ff4d4f' : '#666'"
            size="20"
          />
          <text>点赞 {{ postDetail.likeCount || 0 }}</text>
        </view>
        <view class="action-item" @click="handleStar">
          <wd-icon
            :name="postDetail.isStarred ? 'star-filled' : 'star'"
            :color="postDetail.isStarred ? '#ffb800' : '#666'"
            size="20"
          />
          <text>收藏 {{ postDetail.starCount || 0 }}</text>
        </view>
        <view class="action-item" @click="focusCommentInput">
          <wd-icon name="chat" size="20" color="#666" />
          <text>评论 {{ postDetail.commentCount || 0 }}</text>
        </view>
        <view class="action-item" @click="handleShare">
          <wd-icon name="share" size="20" color="#666" />
          <text>分享</text>
        </view>
      </view>
    </view>

    <!-- 分割线 -->
    <view class="divider">
      <view class="divider-text">全部评论 ({{ comments.length }})</view>
      <!-- <view class="divider-line"></view> -->
    </view>

    <!-- 评论列表 -->
    <view class="comment-list">
      <view v-if="comments.length === 0" class="no-comment">
        <image src="/static/icons/no-comment.png" mode="aspectFit" class="no-comment-icon" />
        <text>还没有评论，快来抢沙发吧~</text>
      </view>

      <view v-for="(comment, index) in comments" :key="index" class="comment-item">
        <view class="comment-user">
          <image
            class="comment-avatar"
            :src="comment.avatar || '/static/avatar.png'"
            mode="aspectFill"
            @tap="viewUserProfile(comment.userId)"
          />
          <view class="comment-user-info">
            <view class="comment-user-name" @tap="viewUserProfile(comment.userId)">
              {{ comment.userName }}
            </view>
            <view class="comment-time">{{ comment.time }}</view>
          </view>
        </view>
        <view class="comment-content">{{ comment.content }}</view>

        <!-- 评论回复 -->
        <view v-if="comment.replies && comment.replies.length > 0" class="reply-list">
          <view v-for="(reply, replyIndex) in comment.replies" :key="replyIndex" class="reply-item">
            <text class="reply-user" @tap="viewUserProfile(reply.userId)">
              {{ reply.userName }}
            </text>
            <text v-if="reply.replyTo" class="reply-to">回复</text>
            <text v-if="reply.replyTo" class="reply-target">@{{ reply.replyTo }}</text>
            ：
            <text class="reply-content">{{ reply.content }}</text>
          </view>
          <view
            v-if="comment.replyCount > comment.replies.length"
            class="more-replies"
            @click="loadMoreReplies(comment.id)"
          >
            查看更多回复({{ comment.replyCount - comment.replies.length }})
          </view>
        </view>

        <view class="comment-actions">
          <view class="comment-like" @click="likeComment(comment.id)">
            <wd-icon
              :name="comment.isLiked ? 'heart-filled' : 'heart'"
              :color="comment.isLiked ? '#ff4d4f' : '#999'"
              size="14"
            />
            <text v-if="comment.likeCount > 0">{{ comment.likeCount }}</text>
          </view>
          <view class="comment-reply" @click="replyToComment(comment)">
            <wd-icon name="chat" size="14" color="#999" />
            <text>回复</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部评论输入框 -->
    <view class="comment-input-container">
      <input
        v-model="commentContent"
        class="comment-input"
        type="text"
        :placeholder="replyTarget ? `回复 ${replyTarget}` : '写评论...'"
        :focus="inputFocus"
        confirm-type="send"
        @confirm="submitComment"
      />
      <view
        class="send-btn"
        :class="{ 'send-active': commentContent.trim().length > 0 }"
        @click="submitComment"
      >
        发送
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";

// 页面参数
const postId = ref("");

// 帖子详情数据
const postDetail = ref({
  id: "",
  userId: "",
  userName: "",
  avatar: "",
  publishTime: "",
  tag: "",
  title: "",
  content: "",
  images: [] as string[],
  location: "",
  likeCount: 0,
  isLiked: false,
  starCount: 0,
  isStarred: false,
  commentCount: 0,
});

// 评论数据
const comments = ref([
  {
    id: "1",
    userId: "user456",
    userName: "李大山",
    avatar: "/static/avatar.png",
    time: "2小时前",
    content: "这个活动非常有意义，我一定会参加！",
    likeCount: 5,
    isLiked: false,
    replyCount: 2,
    replies: [
      {
        id: "1-1",
        userId: "user123",
        userName: "李家族长",
        replyTo: "李大山",
        content: "感谢支持，期待您的参与！",
      },
      {
        id: "1-2",
        userId: "user789",
        userName: "李小明",
        replyTo: "李家族长",
        content: "我也会来参加的！",
      },
    ],
  },
  {
    id: "2",
    userId: "user567",
    userName: "李文华",
    avatar: "/static/avatar.png",
    time: "昨天",
    content: "建议活动可以增加一些互动环节，让年轻一代更有参与感。",
    likeCount: 3,
    isLiked: true,
    replyCount: 1,
    replies: [
      {
        id: "2-1",
        userId: "user123",
        userName: "李家族长",
        replyTo: "李文华",
        content: "这是个很好的建议，我们会考虑的！",
      },
    ],
  },
]);

// 评论输入相关
const commentContent = ref("");
const inputFocus = ref(false);
const replyTarget = ref("");
const replyToCommentId = ref("");

// 页面加载
onLoad((options: any) => {
  if (options && options.id) {
    postId.value = options.id;
    fetchPostDetail(options.id);
    fetchComments(options.id);
  }
});

// 获取帖子详情
const fetchPostDetail = (id: string) => {
  // TODO: 从服务器获取帖子详情
  // 模拟数据
  postDetail.value = {
    id: id,
    userId: "user123",
    userName: "李家族长",
    avatar: "https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/d560fd508cce44b5af0f7cc0e140b9e6.jpg",
    publishTime: "2小时前",
    tag: "活动",
    title: "2024年李氏家族线下家族分享会",
    content:
      "《陇西荟》可筹办多彩线下家族聚会，深化成员情谊，促进宗亲深度交流。同时，举办产品分享盛会，既为企业拓宽宣传渠道，又助宗亲学习养生之道，有效提升用户黏性，共筑美好时光。欢迎各位宗亲积极参与。活动地点：博阳李家，活动时间：上午9点。",
    images: ["https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/0a345d867e234edca9048c330a16887b.png"],
    location: "李氏宗祠",
    likeCount: 56,
    isLiked: false,
    starCount: 12,
    isStarred: false,
    commentCount: 28,
  };
};

// 获取评论列表
const fetchComments = (postId: string) => {
  // TODO: 从服务器获取评论列表
  // 使用模拟数据
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 显示更多操作菜单
const showMoreActions = () => {
  uni.showActionSheet({
    itemList: ["举报", "分享到微信", "分享到朋友圈", "复制链接"],
    success: (res) => {
      console.log("选择了第" + (res.tapIndex + 1) + "个按钮");
    },
  });
};

// 预览图片
const previewImage = (images: string[], current: number) => {
  uni.previewImage({
    urls: images,
    current: images[current],
  });
};

// 点赞帖子
const handleLike = () => {
  if (!postDetail.value.isLiked) {
    postDetail.value.likeCount++;
    postDetail.value.isLiked = true;
  } else {
    postDetail.value.likeCount--;
    postDetail.value.isLiked = false;
  }
  // TODO: 发送点赞请求到服务器
};

// 收藏帖子
const handleStar = () => {
  if (!postDetail.value.isStarred) {
    postDetail.value.starCount++;
    postDetail.value.isStarred = true;
  } else {
    postDetail.value.starCount--;
    postDetail.value.isStarred = false;
  }
  // TODO: 发送收藏请求到服务器
};

// 分享帖子
const handleShare = () => {
  uni.showShareMenu({
    withShareTicket: true,
  });
};

// 聚焦评论输入框
const focusCommentInput = () => {
  replyTarget.value = "";
  replyToCommentId.value = "";
  inputFocus.value = true;
};

// 回复评论
const replyToComment = (comment: any) => {
  replyTarget.value = comment.userName;
  replyToCommentId.value = comment.id;
  inputFocus.value = true;
};

// 提交评论
const submitComment = () => {
  if (commentContent.value.trim() === "") return;

  // 添加新评论
  if (!replyToCommentId.value) {
    const newComment = {
      id: Date.now().toString(),
      userId: "my-user-id",
      userName: "我",
      avatar: "/static/avatar.png",
      time: "刚刚",
      content: commentContent.value,
      likeCount: 0,
      isLiked: false,
      replyCount: 0,
      replies: [],
    };
    comments.value.unshift(newComment);
    postDetail.value.commentCount++;
  } else {
    // 添加回复
    const targetComment = comments.value.find((c) => c.id === replyToCommentId.value);
    if (targetComment) {
      if (!targetComment.replies) {
        targetComment.replies = [];
      }

      const newReply = {
        id: `${replyToCommentId.value}-${Date.now()}`,
        userId: "my-user-id",
        userName: "我",
        replyTo: replyTarget.value,
        content: commentContent.value,
      };

      targetComment.replies.push(newReply);
      targetComment.replyCount++;
      postDetail.value.commentCount++;
    }
  }

  // 重置输入框
  commentContent.value = "";
  replyTarget.value = "";
  replyToCommentId.value = "";
  inputFocus.value = false;

  // TODO: 发送评论到服务器
};

// 点赞评论
const likeComment = (commentId: string) => {
  const comment = comments.value.find((c) => c.id === commentId);
  if (comment) {
    if (!comment.isLiked) {
      comment.likeCount++;
      comment.isLiked = true;
    } else {
      comment.likeCount--;
      comment.isLiked = false;
    }
    // TODO: 发送点赞请求到服务器
  }
};

// 加载更多回复
const loadMoreReplies = (commentId: string) => {
  // TODO: 从服务器加载更多回复
  console.log("加载更多回复", commentId);
};

// 查看用户资料
const viewUserProfile = (userId: string) => {
  if (!userId) return;

  uni.navigateTo({
    url: `/pages/mine/profile/card?id=${userId}`,
  });
};
</script>

<style lang="scss">
.post-detail {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 100rpx; // 为底部输入框留出空间
}

.navbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 30rpx;
  background-color: #fff;
  position: sticky;
  top: 0;
  z-index: 100;
}

.back-btn,
.more-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.navbar-title {
  font-size: 32rpx;
  font-weight: bold;
}

.post-content {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.post-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.user-info {
  display: flex;
  align-items: center;
}

.avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  margin-right: 16rpx;
}

.user-name {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}

.post-time {
  font-size: 24rpx;
  color: #999;
  margin-top: 4rpx;
}

.post-tag {
  font-size: 24rpx;
  color: #3b8dff;
  background-color: rgba(59, 141, 255, 0.1);
  padding: 4rpx 16rpx;
  border-radius: 30rpx;
}

.post-body {
  margin-bottom: 30rpx;
}

.post-title {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
  color: #333;
}

.post-text {
  font-size: 28rpx;
  color: #333;
  line-height: 1.6;
  margin-bottom: 20rpx;
  white-space: pre-wrap;
}

.post-images {
  margin-top: 20rpx;
}

.post-image {
  width: 100%;
  border-radius: 8rpx;
  margin-bottom: 20rpx;
}

.post-location {
  display: flex;
  align-items: center;
  margin-top: 20rpx;
  font-size: 24rpx;
  color: #999;

  text {
    margin-left: 8rpx;
  }
}

.post-actions {
  display: flex;
  justify-content: space-around;
  padding-top: 20rpx;
  border-top: 1rpx solid #f0f0f0;
}

.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;

  text {
    font-size: 24rpx;
    color: #666;
    margin-top: 10rpx;
  }
}

.divider {
  position: relative;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  padding: 0 30rpx;
}

.divider-line {
  flex: 1;
  height: 1rpx;
  background-color: #e0e0e0;
}

.divider-text {
  padding-right: 20rpx;
  font-size: 28rpx;
  color: #999;
}

.comment-list {
  background-color: #fff;
  padding: 0 30rpx;
}

.no-comment {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 60rpx 0;
  color: #999;
  font-size: 28rpx;
}

.no-comment-icon {
  width: 120rpx;
  height: 120rpx;
  margin-bottom: 20rpx;
}

.comment-item {
  padding: 30rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.comment-item:last-child {
  border-bottom: none;
}

.comment-user {
  display: flex;
  margin-bottom: 16rpx;
}

.comment-avatar {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  margin-right: 16rpx;
}

.comment-user-name {
  font-size: 28rpx;
  font-weight: 500;
  color: #333;
}

.comment-time {
  font-size: 24rpx;
  color: #999;
  margin-top: 4rpx;
}

.comment-content {
  font-size: 28rpx;
  color: #333;
  line-height: 1.5;
  margin-bottom: 16rpx;
}

.reply-list {
  background-color: #f8f8f8;
  border-radius: 8rpx;
  padding: 16rpx;
  margin-top: 10rpx;
}

.reply-item {
  font-size: 26rpx;
  margin-bottom: 10rpx;
  line-height: 1.5;
}

.reply-user {
  color: #3b8dff;
  font-weight: 500;
}

.reply-to,
.reply-content {
  color: #333;
}

.reply-target {
  color: #3b8dff;
}

.more-replies {
  font-size: 26rpx;
  color: #3b8dff;
  margin-top: 10rpx;
}

.comment-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 16rpx;
}

.comment-like,
.comment-reply {
  display: flex;
  align-items: center;
  margin-left: 30rpx;

  text {
    font-size: 24rpx;
    color: #999;
    margin-left: 6rpx;
  }
}

.comment-input-container {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: #fff;
  border-top: 1rpx solid #f0f0f0;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.comment-input {
  flex: 1;
  height: 70rpx;
  background-color: #f5f5f5;
  border-radius: 35rpx;
  padding: 0 30rpx;
  font-size: 28rpx;
}

.send-btn {
  width: 120rpx;
  height: 70rpx;
  line-height: 70rpx;
  text-align: center;
  font-size: 28rpx;
}
</style>
